package org.zhengquan.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.zhengquan.util.JsonMapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author zhengquan
 * @date 2017/10/27
 */
@Slf4j
public class HttpIntercepter extends HandlerInterceptorAdapter {
    private static final String START_TIME = "startTime";

    //处理之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        Map params = request.getParameterMap();
        log.info("request start. url:{}. params:{}", url, JsonMapper.obj2Str(params));
        Long startTime = System.currentTimeMillis();
        request.setAttribute(START_TIME, startTime);
        return true;
    }


    //任何情况下结束之后(包括异常)
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String url = request.getRequestURL().toString();
        Long startTime = (Long) request.getAttribute(START_TIME);
        Long endTime = System.currentTimeMillis();
        log.info("request finish. url:{}. cost:{}", url, endTime - startTime);
        removeThreadLocalInfo();
    }

    private void removeThreadLocalInfo() {
        RequestHolder.remove();
    }
}
